import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import rateLimit from 'express-rate-limit';

// 创建速率限制器
const limiter = rateLimit({
    windowMs: 1000, // 1秒钟
    max: 4, // 每个 IP 地址每秒钟最多 4 次请求
    // message: 'Too many requests, please try again later.',
    handler: (req: Request, res: Response) => {
        res.status(429).json({
            status: 'error',
            message: 'Too many requests, please try again later.',
            retryAfter: 1000, // 在限制后可重试的时间，单位是毫秒
        });
    },
});

@Injectable()
export class RateLimitMiddleware implements NestMiddleware {
    use(req: Request, res: Response, next: NextFunction) {
        limiter(req, res, next); // 应用速率限制器
    }
}